/**
 * Created by charsen on 16/6/2.
 */
directives.directive('addNewTable', ["$rootScope", "tools", "$timeout", function ($rootScope, tools, $timeout) {
    return {
        restrict: 'AE',
        scope: {},
        replace: true,
        link: function (scope, element, attr) {
            $(element).height(document.documentElement.clientHeight * 0.8);
            $(element).find(".addTableBox").height(document.documentElement.clientHeight * 0.8-177);
            scope.databases = [];
            scope.dbTables = [];
            scope.tbColumns = [];

            var sourceName = "";

            scope.tableName = "";
            scope.tableDesc = "";
            scope.databaseName = "";



            $rootScope.$on('ADD_TABLE_EV', function (e, sourceId, sourceName_) {

               // $timeout(function(){$rootScope.$broadcast("loading_Start_EV");},50);
                $(element).modal('show');

                scope.tableListShown = true;

                sourceName = sourceName_;


                /*console.log({sourceId: sourceId,
                    sourceName: sourceName_});*/


                tools.get({
                    method: 'POST',
                    url: '/Ibm-Client/getDatabases.htm',
                    data: {
                        sourceId: sourceId,
                        sourceName: sourceName
                    },
                    succ: function (resp) {
                        if (resp.success) {
                            scope.databases = resp.value;
                            $timeout(function(){
                                $(".dropdown").dropdown();
                            });
                            //scope.databaseName = scope.databases[0].dataBaseName;
                            //getDatabaseTables(sourceName_, scope.databases[0].dataBaseName);
                        }else{
                            $timeout(function(){
                                $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                                return;
                            },500);
//                            alert(resp.message);
                        }
                    }
                });
            });




            // 切换数据库
            scope.changeDataBase = function (databaseName) {
                $rootScope.$broadcast("loading_Start_EV");
                scope.dbTables=[];
                scope.databaseName = databaseName;

                getDatabaseTables(sourceName, databaseName);
            };

            // 根据数据库名获取表
            function getDatabaseTables(sourceName, databaseName) {
                tools.get({
                    url: '/Ibm-Client/getDatabaseTables.htm',
                    method: 'POST',
                    data: {
                        databaseName: databaseName,
                        sourceName: sourceName,
                        currentPageNo: 1,
                        resultSize: 20000
                    },
                    succ: function (resp) {
                        if (resp.success) {
                            $rootScope.$broadcast("loading_End_EV");
                            scope.dbTables = resp.value;
                            angular.forEach(scope.dbTables, function (table) {
                                table.shown = true;
                                table.isAdded = false;

                            });
                           // console.log("db");
                           // console.log(scope.dbTables);

                        }else{
                            $timeout(function(){
                                $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                                return;
                            },500);
//                            alert(resp.message);
                        }
                    }
                });
            }

            function delDatabaseTable(databaseName) {
                angular.forEach(scope.dbTables, function (tb) {
                    if (tb.databaseName == databaseName) {
                        tb.added = true;
                    }
                });
            }

            // 检索表
            scope.search = {
                name: ''
            };
            scope.$watch('search.name', function (n, o) {
                angular.forEach(scope.dbTables, function (table) {
                    if (table.tableName.indexOf(n) != -1 || table.tableDesc.indexOf(n) != -1) {
                        table.shown = true;
                    } else {
                        table.shown = false;
                    }
                });
            });


            scope.closeAddTable = function(){
               // console.log("close add table");
                $rootScope.$broadcast("loading_End_EV");
            };



            scope.Whichindex=null;

            // 选择字段导入
            scope.tableListShown = true;
            scope.getDatabaseTableColumns = function (tableName, tableDesc, index) {

                scope.Whichindex = index;

                scope.tableListShown = false;

                scope.tableDesc = tableDesc || tableName;
                scope.tableName = tableName;

                tools.get({
                    url: '/Ibm-Client/getDatabaseTableColumns.htm',
                    method: 'POST',
                    data: {
                        databaseName: scope.databaseName,
                        tableName: scope.tableName
                    },
                    succ: function (resp) {
                        if (resp.success) {

                            scope.tbColumns = resp.value;
                            angular.forEach(scope.tbColumns, function (column) {
                                column.selected = true;
                            });
                        }else{
//                            alert(resp.message);
                            $timeout(function(){
                                $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                                return;
                            },500);
                        }
                    }
                });
            };

            scope.selectedAll = {
                isSelected: true
            };
            scope.$watch('selectedAll.isSelected', function (nv) {
               // console.log(nv);
                angular.forEach(scope.tbColumns, function (column) {
                    column.selected = nv;
                });
            });


            //是否选择input checkbox
            scope.checkIt = function(index){
                if(scope.tbColumns[index].selected){
                    $timeout(function(){
                        scope.tbColumns[index].selected = false;
                    },10);
                }else{
                    $timeout(function(){
                        scope.tbColumns[index].selected = true;
                    },10);
                }
            };

            scope.importDatabaseTable = function (e) {
                var $tar = $(e.target);
                var columnNames = [];
                var columnDescs = [];

               // console.log(scope.tbColumns);
             //   return;
                angular.forEach(scope.tbColumns, function (column) {
                    if (column.selected) {
                        columnNames.push(column.columnName);
                        columnDescs.push(column.columnDesc);
                    }
                });
                if($.isEmptyObject(columnNames)){
                    return;
                }
                $tar.text("正在添加...");

                $.ajax({
//                    method: 'POST',
                    type: 'POST',
                    url: '/Ibm-Client/importDatabaseTable.htm',
                    data: {
                        databaseName: scope.databaseName,
                        tableName: scope.tableName,
                        tableDesc: scope.tableDesc,
                        columnNames: columnNames.join(','),
                        columnDescs: columnDescs.join(',')
                    },
                    success: function (resp) {
                        resp = $.parseJSON(resp);
                        if (resp.success) {

                            scope.dbTables[scope.Whichindex].isAdded=true;

                            $tar.text("添加成功!");
                            $rootScope.$broadcast("addNewTable_EV");
                            $timeout(function () {
                                $tar.text("确定添加");
                                scope.tableListShown = true;
                               // console.log("scope.dbTables:"+scope.dbTables)
                            }, 1500);
                          //  console.log(scope.tbIsAdded);

                        }else{
                            $tar.text("添加失败!");
                            $timeout(function () {
                                $tar.text("确定添加");
                                scope.tableListShown = true;
                            }, 1500);
//                            alert(resp.message);
                            $timeout(function(){
                                $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                                return;
                            },500);
                        }
                    }
                });
            }
        },
        templateUrl: "/trend-new-BI/app/components/dbManager/addNewTable/addNewTableView.html"
    }
}]);